"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.default = void 0;

var _react = _interopRequireWildcard(require("react"));

var _ahooks = require("ahooks");

var _antd = require("antd");

var _tools = require("../../tools");

var _tools2 = require("./tools");

function _getRequireWildcardCache(nodeInterop) { if (typeof WeakMap !== "function") return null; var cacheBabelInterop = new WeakMap(); var cacheNodeInterop = new WeakMap(); return (_getRequireWildcardCache = function _getRequireWildcardCache(nodeInterop) { return nodeInterop ? cacheNodeInterop : cacheBabelInterop; })(nodeInterop); }

function _interopRequireWildcard(obj, nodeInterop) { if (!nodeInterop && obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { default: obj }; } var cache = _getRequireWildcardCache(nodeInterop); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj.default = obj; if (cache) { cache.set(obj, newObj); } return newObj; }

var Lane = function Lane(_ref) {
  var {
    data,
    onActions,
    onLoad,
    assets,
    setCurrentCell,
    zoom = 1,
    isFullScreen,
    setCanRedo,
    setCanUndo,
    onUndoOrRedo
  } = _ref;
  var containerRef = (0, _react.useRef)(null);
  var laneRef = (0, _react.useRef)(null);
  var laneTitleRef = (0, _react.useRef)(null);
  var laneWrapperRef = (0, _react.useRef)(null);
  var miniMapRef = (0, _react.useRef)(null);
  var menuRef = (0, _react.useRef)(null);
  var [graph, setGraph] = (0, _react.useState)();
  (0, _react.useEffect)(() => {
    if (!graph) return;
    var nodes = graph.model.getNodes();

    if (Array.isArray(nodes)) {
      nodes.forEach(n => {
        var {
          type,
          image
        } = n.data;

        if (type === 'node') {
          n.attr('itemTag/xlinkHref', assets[image]);
        }
      });
    }
  }, [assets, graph]); // 画布事件响应

  var handlerActions = (0, _ahooks.usePersistFn)(action => {
    onActions && onActions(action);
    onVisibleChange(false);
  }); // 删除连接 防抖

  var {
    run: onRemoveEdge
  } = (0, _ahooks.useDebounceFn)(edge => {
    if (!edge.data) return;
    setCurrentCell(edge);
    (0, _tools.nextTick)(() => handlerActions('delete'));
  }, {
    wait: 100
  });
  var syncLaneTitle = (0, _ahooks.usePersistFn)(() => {
    var x6Graph = containerRef.current;
    var laneTitleSvg = laneTitleRef.current;
    if (!x6Graph || !laneTitleSvg) return; // const x6GraphParent = x6Graph.parentNode;

    var x6GraphLaneShapes = x6Graph.querySelectorAll('g[data-shape="lane"]');
    var laneTitleStage = laneTitleSvg.querySelector('.x6-graph-svg-stage');
    laneTitleStage.innerHTML = '';
    Array.from(x6GraphLaneShapes).forEach(laneShapeNode => {
      var laneTitleLaneShape = laneShapeNode.cloneNode(true);
      Array.from(laneTitleLaneShape.childNodes).forEach(node => {
        var className = node.getAttribute('class');

        if (className === 'laneBody') {
          laneTitleLaneShape.removeChild(node);
        } else if (className === 'resizeBorder') {
          node.setAttribute('width', '30');
        }
      });
      laneTitleStage.appendChild(laneTitleLaneShape);
    });
    syncContainerSize();
    x6Graph.style.transformOrigin = 'left top';
    x6Graph.style.transform = "scale(".concat(zoom, ")");
    laneTitleSvg.style.transformOrigin = 'left top';
    laneTitleSvg.style.height = x6Graph.offsetHeight + 'px';
    laneTitleSvg.style.transform = "scale(".concat(zoom, ")");
  }); // 同步画布容器的尺寸

  var syncContainerSize = (0, _ahooks.usePersistFn)(() => {
    if (!graph || !laneWrapperRef.current || !containerRef.current) return;
    var laneNodeList = graph.getNodes().filter(node => node.shape === 'lane');
    var maxHeight = Math.max(laneWrapperRef.current.parentNode.clientHeight || 0, laneNodeList.reduce((p, item) => p + item.size().height, 0) + 50);
    containerRef.current.style.height = maxHeight + 'px';
    if (!containerRef.current.parentNode) return;
    containerRef.current.parentNode.style.height = containerRef.current.offsetHeight * zoom + 'px';
  }); // 监控缩放

  (0, _react.useEffect)(() => {
    // 当数据发生变化时，需要等画布发生变化后再去同步节点才能准确
    (0, _tools.nextTick)(() => {
      var x6Graph = containerRef.current;
      if (!graph || !x6Graph) return;
      syncLaneTitle();
      var x6GraphParent = x6Graph.parentNode;
      if (!x6GraphParent) return;
      x6GraphParent.style.height = x6Graph.offsetHeight * zoom + 'px';
    });
  }, [zoom, graph, data]);

  var handleMenuClick = _ref2 => {
    var {
      key
    } = _ref2;
    handlerActions(key);
  }; // 改变泳道高度


  var onLaneReszie = (0, _ahooks.usePersistFn)((laneNode, width, height, minHeight) => {
    if (height < minHeight || !graph) return;else laneNode.size(width, height);
    var laneNodeList = graph.getNodes().filter(node => node.shape === 'lane');
    var laneIndex = laneNodeList.findIndex(lane => lane.id === laneNode.id);

    if (laneIndex > -1) {
      // 改变当前泳道的高度
      var currentY = laneNode.position().y + height; // 调整泳道内节点的Y坐标

      var children = laneNode.getChildren();

      if (Array.isArray(children) && children.length) {
        children.forEach(child => {
          var {
            height: ch
          } = child.size();
          var {
            x: cx,
            y: cy
          } = child.position();

          if (cy + ch > currentY) {
            child.position(cx, currentY - ch);
          }
        });
      } // 调整位置在当前泳道下方的泳道的位置


      laneNodeList.slice(laneIndex + 1).forEach(nextLaneNode => {
        var {
          x: laneX,
          y: laneY
        } = nextLaneNode.position();
        nextLaneNode.position(laneX, currentY); // 调整泳道位置的同时也要调整泳道内子节点的位置

        var children = nextLaneNode.getChildren();

        if (Array.isArray(children) && children.length > 0) {
          children.forEach(childNode => {
            var {
              x: childX,
              y: childY
            } = childNode.position();
            var offsetY = childY - laneY;
            childNode.position(childX, currentY + offsetY);
          });
        }

        currentY += nextLaneNode.size().height;
      });
    }
  }); // 添加连接

  var onAddLink = edge => {
    setCurrentCell(edge);
    (0, _tools.nextTick)(() => handlerActions('add'));
  };

  var initPage = (0, _ahooks.usePersistFn)(() => {
    if (!containerRef.current || !laneWrapperRef.current || !laneWrapperRef.current // !miniMapRef.current
    ) {
      return;
    }

    var gh = graph;

    if (!gh) {
      (0, _tools2.registerLane)({
        width: containerRef.current.clientWidth,
        height: 200
      });
      (0, _tools2.registerNode)();
      (0, _tools2.registerModuleNode)();
      (0, _tools2.registerEdge)();
      gh = (0, _tools2.getGraph)(containerRef.current, miniMapRef.current, {
        onAddLink
      });
      (0, _tools2.registerNodeMenuContext)(gh, menuRef, setCurrentCell);
      (0, _tools2.registerResizeNode)(gh);
      (0, _tools2.registerResizeLane)(gh, onLaneReszie);
      (0, _tools2.registerEdgeRemove)(gh, onRemoveEdge);
      (0, _tools2.registerNodeNumChange)(gh);
      (0, _tools2.registerAutoSave)(gh);
      (0, _tools2.registerHistory)(gh, {
        setCanRedo,
        setCanUndo,
        onUndoOrRedo
      });
      (0, _tools2.registerKeyboard)(gh, onActions);
    } else {
      gh.clearCells();
    }

    var cells = [];
    var {
      laneList: laneDataList,
      // 泳道数据
      nodeList: nodeDataList,
      // 节点数据
      linkList: linkDataList,
      // 连线数据
      width,
      height
    } = data; // 计算页面宽高，并将宽度赋值给泳道，并在泳道的上下留出一定的空间方便拖拽

    var maxWidth = Math.max(containerRef.current.clientWidth, width || 0);
    var maxHeight = Math.max(laneWrapperRef.current.parentNode.clientHeight, height || 0);
    containerRef.current.style.width = maxWidth + 'px';
    containerRef.current.style.height = maxHeight + 'px';
    laneDataList.forEach(item => {
      item.width = maxWidth;
      if (!item.attrs) item.attrs = (0, _tools.getLaneStyle)(Number(item.id) - 1);
    }); // 泳道map方便查找

    var laneMap = {}; // 泳道图形化

    laneDataList.forEach(item => {
      var lane = gh.createNode(item);
      (0, _tools2.registerLaneCellChange)(lane, () => (0, _tools.nextTick)(() => syncLaneTitle()));
      cells.push(lane);
      laneMap[lane.id] = lane;
    }); // 节点图形化

    var nodeInLaneMap = {};
    nodeDataList.forEach(item => {
      var {
        image,
        preId,
        bgImage
      } = item.data || {};
      var node = gh.createNode(item);
      node.attr({
        itemTag: {
          xlinkHref: assets[image]
        },
        backgorund: {
          xlinkHref: assets[bgImage]
        }
      });
      cells.push(node);
      if (!nodeInLaneMap[preId]) nodeInLaneMap[preId] = [];
      nodeInLaneMap[preId].push(node);
    }); // 连线图形化

    linkDataList.forEach(item => {
      var link = gh.createEdge(item);
      cells.push(link);
    });
    gh.resetCells(cells);
    Object.keys(nodeInLaneMap).forEach(laneId => {
      var lane = laneMap[laneId];
      var nodeList = nodeInLaneMap[laneId];
      lane.setChildren(nodeList);
    });
    gh.positionRect({
      x: 0,
      y: 0,
      width: maxWidth,
      height: maxHeight
    }, 'top-left');
    setGraph(gh);
    onLoad(gh);
    syncLaneTitle();
    gh.cleanHistory();
  });
  (0, _react.useEffect)(() => {
    initPage();
  }, [data]);
  (0, _ahooks.useUpdateEffect)(() => {
    setTimeout(() => {
      initPage();
    }, 500);
  }, [isFullScreen]);

  var menu = /*#__PURE__*/_react.default.createElement(_antd.Menu, {
    onClick: handleMenuClick
  }, /*#__PURE__*/_react.default.createElement(_antd.Menu.Item, {
    key: "edite"
  }, /*#__PURE__*/_react.default.createElement("a", {
    rel: "noopener noreferrer"
  }, "\u7F16\u8F91")), /*#__PURE__*/_react.default.createElement(_antd.Menu.Item, {
    key: "delete"
  }, /*#__PURE__*/_react.default.createElement("a", {
    rel: "noopener noreferrer"
  }, "\u5220\u9664")));

  var onVisibleChange = visible => {
    if (!visible) {
      setTimeout(() => {
        if (!menuRef.current) return;
        menuRef.current.style.left = '-100px';
        menuRef.current.style.top = '-100px';
      }, 100);
    }
  };

  return /*#__PURE__*/_react.default.createElement("div", {
    className: "ra-arch-laneWrapper",
    ref: laneWrapperRef
  }, /*#__PURE__*/_react.default.createElement(_antd.Dropdown, {
    overlay: menu,
    placement: "bottomLeft",
    onVisibleChange: onVisibleChange
  }, /*#__PURE__*/_react.default.createElement("div", {
    style: {
      position: 'absolute',
      width: 10,
      height: 10,
      background: 'transparent',
      left: -100,
      top: -100,
      zIndex: 999
    },
    ref: menuRef
  })), /*#__PURE__*/_react.default.createElement("div", {
    className: "ra-arch-mimiMap",
    ref: miniMapRef
  }), /*#__PURE__*/_react.default.createElement("div", {
    className: "ra-arch-lane",
    ref: laneRef
  }, /*#__PURE__*/_react.default.createElement("div", {
    ref: containerRef
  }), /*#__PURE__*/_react.default.createElement("svg", {
    width: 30,
    style: {
      left: 0,
      top: 0
    },
    height: "100%",
    ref: laneTitleRef,
    className: "x6-graph-svg",
    xmlns: "http://www.w3.org/2000/svg"
  }, /*#__PURE__*/_react.default.createElement("g", {
    className: "x6-graph-svg-viewport"
  }, /*#__PURE__*/_react.default.createElement("g", {
    className: "x6-graph-svg-stage"
  })))));
};

var _default = /*#__PURE__*/_react.default.memo(Lane);

exports.default = _default;